package com.zwr.sheller.customer.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.zwr.sheller.core.pojo.Order;
import com.zwr.sheller.core.pojo.OrderSku;
import com.zwr.sheller.core.pojo.OriginOrder;
import com.zwr.sheller.core.pojo.Sku;
import com.zwr.sheller.customer.Service.OrderService;
import com.zwr.sheller.customer.mapper.OrderSkuMapper;
import com.zwr.sheller.customer.mapper.SkuMapper;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@RestController
@CrossOrigin
public class PayController {
    @Autowired(required = false)
    private OrderService orderService;
    @Autowired(required = false)
    private OrderSkuMapper orderSkuMapper;
    @Autowired(required = false)
    private SkuMapper skuMapper;

    /**
     * 参数中应该包含订单中的信息
     * 访问改接口，通过远程调用支付宝接口，支付宝会返回一个form字符串
     */
    @RequestMapping("/pay")
    @ApiOperation(value = "支付接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNum",value = "订单编号",dataType = "Long"),
    })
    public String pay(Long orderNum){
        String severurl = "https://openapi.alipaydev.com/gateway.do";
        AlipayClient alipayClient = new DefaultAlipayClient(severurl, "2021000118686844", "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCd3+3wOoqPunxiMvDBFQofogl7sqKn0cNMNFKEoHsiCHa3J4S6CHQzjJQWxkkT/SCwrPcM2opZYJFoPGyJTdm3I2GCbcECfQnssvUDzdg3u6mXpu3HlkoKRhZI7OcGKOZnjegrE6Kt7cupNoZbXgQuPFDNTyX61a+rZAKX3SS2qY1S2KsUn9PKQxJ1sRIgk6Hw1+3r/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HMqGtXqxstLucUpGMaRb9uLM2WRQFNrKfXTNKY/KUs0+UvH2W6gpxS8LWoLtlPBP1WB9mhnsftnQ6RYyhBNynzxsSC9FXySV7NMyF/iDOS9arIiECgYB8wZTklLP7pyfnhdOnUn92VFCoUYaKk+pRMdlhmYfR0K7+N59k7PEzvVw8I54wYAQ4IYLjuLw9gXsui8mbX7KcG1qxET7U0YemZDVH4kHpAJXQvAl+Hl//Vziay9jqyEAuzIo+3zV3GufoQsEnUIObcgojYy7PRUDOnSqhh44mag==", "json"
                , "UTF-8", "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnd/t8DqKj7p8YjLwwRUKH6IJe7Kip9HDTDRShKB7Igh2tyeEugh0M4yUFsZJE/0gsKz3DNqKWWCRaDxsiU3ZtyNhgm3BAn0J7LL1A83YN7upl6btx5ZKCkYWSOznBijmZ43oKxOire3LqTaGW14ELjxQzU8l+tWvq2QCl90ktqmNUtirFJ/TykMSdbESIJOh8Nft6/0uR21B6EmMBkx8YIfvkdEsH/FVxP1vKyY4dWv3ntC8La217ciWtV8jIehaPZI82vpj2ydC/w4ylbtsikjhhWg16NVvufojDEIgZ9ogBse3QXC3Rb2z1K+KNQMb6LwxbZMdyqwAoGdyK+IgxQIDAQAB",
                "RSA2"); //获得初始化的AlipayClient
        //找到订单
        OriginOrder order = new OriginOrder();
        order.setOrderNum(orderNum.toString());
        OriginOrder orderFromData = orderService.selectByFeatures(order);
        System.out.println(orderFromData);
        //找对应的SkuId 和 SkuNum
        Example example = new Example(OrderSku.class);
        example.createCriteria().andEqualTo("orderId",orderFromData.getOrderId());
        List<OrderSku> orderSkus = orderSkuMapper.selectByExample(example);
        //找对应的SkuPrice,并计算需要支付的钱
        Sku sku = new Sku();
        Double sum = 0.0;
        for (OrderSku ordersku : orderSkus) {
            sku.setSkuId(ordersku.getSkuId());
            Sku skuFromData = skuMapper.selectOne(sku);
            sum += ordersku.getSkuNum()*skuFromData.getSkuPrice()-orderFromData.getOrderDiscountedPrice();
        }
        System.out.println(sum);



        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request

        //设置返回地址
        alipayRequest.setReturnUrl("http://localhost:8081/order/updateOrder");
        //设置通知地址
        /*alipayRequest.setNotifyUrl("http://domain.com/CallBack/notify_url.jsp");*///在公共参数中设置回跳和通知地址


        alipayRequest.setBizContent("{\"order_num\":\""+ orderNum +"\","
                + "\"total_money\":\""+ sum +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
     return  form;
    }

}
